<template>
    <div>
        <el-dialog :model-value="dialogVisible" :before-close="handleClose" title="新增食材" width="500">
            <el-form :model="form" ref="ruleFormRef" :rules="rules">

                <div>


                    <!-- 物料名称 -->
                    <el-form-item label="物料名称" :label-width="formLabelWidth" prop="name">
                        <el-input v-model="form.name" autocomplete="off" />
                    </el-form-item>

                    <!-- 单位 -->
                    <el-form-item label="单位" :label-width="formLabelWidth" prop="newPwd">
                        <!-- <el-input v-model="form.unit" autocomplete="off" /> -->
                        <el-select v-model="form.unit" placeholder="请选择单位">
                            <el-option v-for="item in unitOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>


                    <!-- 供应商 -->
                    <el-form-item label="供应商" :label-width="formLabelWidth" prop="newPwd">
                        <!-- <el-input v-model="form.supplierId" autocomplete="off" /> -->
                        <el-select v-model="form.supplierId" placeholder="请选择供应商">
                            <el-option v-for="item in supplierOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </div>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="changeParent(false)">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">添加</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang='ts'>
import { addCompany, getCompany } from '@/apis/branch/branch';
import type { Company } from '@/apis/branch/type';
import { addFood, getFood, getSuppliers, updateFood } from '@/apis/diet/food';
import type { FoodsList } from '@/apis/diet/type';
import { resetPwd } from '@/apis/resetPwd/resetPwd';
import type { reset } from '@/apis/resetPwd/type';
import { doEncrypt } from '@/utils/cryptoUtil';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { ref, reactive, onUpdated } from 'vue';
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    changeParent: {
        type: Function,
        default: () => { }
    },
    changeId: {
        type: Number,
        default: 0
    }
})
const emit = defineEmits(['closeDialog'])
const close = () => {
    emit('closeDialog', false)
}
// 输入框宽度
const formLabelWidth = '140px'

// 获取单条食材信息
const getFoodById = async (id: number) => {
    let res = await getFood(id)
    // console.log('单条食材', res);
    form.value = res
    // console.log(form.value);

}



onUpdated(() => {

    if (props.changeId == 0) {
        form.value = {
            name: '',
            supplierId: undefined,
            id: 0,
            unit: '',
        }
    }

    if (props.changeId != 0) {
        // console.log(props.changeId);
        getFoodById(props.changeId)
    }
})


// 点击遮罩层关闭弹窗的函数
const handleClose = (done: () => void) => {
    props.changeParent(false)
    close();

    form.value = {
        name: '',
        supplierId: undefined,
        id: 0,
        unit: '',
    }

}

// 表单
const formRef = ref<FormInstance | null>(null);
const ruleFormRef = ref<FormInstance>()
const form = ref<FoodsList>({
    name: '',
    supplierId: undefined,
    id: 0,
    unit: ''
})



// 表单提示

const rules = reactive<FormRules<FoodsList>>({
    name: [
        { required: true, message: '请输入物料名称', trigger: 'blur' },
    ]

})


// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) {
        ElMessage.error('表单未正确初始化，请刷新页面重试');
        return
    }

    console.log(form.value);
    await formEl.validate(async (valid: boolean) => {
        if (valid) {

            if (form.value.id == 0) {
                // 添加物料
                let res = await addFood(form.value)
                // console.log(res);
            }else{
                let res = await updateFood(form.value)
                // console.log(res);
            }

            ElMessage.success(form.value.id == 0 ? '添加成功':'修改成功');
            // 关闭弹窗
            props.changeParent(false);
            // 清空表单数据
            form.value = {
                name: '',
                unit: '',
                id: 0,
                supplierId: 0
            };
            close();
        } else {
            console.log('error submit!!');
            form.value = {
                name: '',
                unit: '',
                id: 0,
                supplierId: undefined
            };
            // 不需要返回 false，直接结束函数即可
        }
    });
};


// 获取供应商
const getSupplierList = async () => {
    let res = await getSuppliers({ page: 1, pageSize: 100 });
    // console.log('供应商', res);
    console.log('供应商', res.list);
    if (res.list) {
        res.list.forEach((item: any) => {
            supplierOptions.push({
                value: item.id,
                label: item.name
            });
        });
    }

};
getSupplierList()

interface options {
    value: number,
    label: string
}
// 供应商选择器
const supplierOptions = <options[]>[]


// 单位选择器
const unitOptions = [
    {
        value: '斤',
        label: '斤',
    },
    {
        value: '吨',
        label: '吨',
    },
    {
        value: '克',
        label: '克',
    },
    {
        value: '个',
        label: '个',
    }
]


</script>

<style scoped lang='less'></style>